package org.judo.menu;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.judo.database.JudoDatabaseManager;

public class MenuManager
{
	private static HashMap<String,Menu> menus = new HashMap<String,Menu>();
	
	public static String[] menus()
	{
		return menus.keySet().toArray(new String[0]);
	}
	
	public static Menu menu(String menuName)
	{
		return menus.get(menuName);
	}
	
	public static void addMenu(Menu menu)
	{
		menus.put(menu.getName(),menu);
	}
	
	public static void loadDefinedMenus()
	{
		InputStream is = null;
		
		try
		{
			is =(new JudoDatabaseManager().getClass()).getResourceAsStream(
					"/menus.xml");
			
			SAXBuilder builder = new SAXBuilder();
			Document doc = builder.build(is);
			Element root = doc.getRootElement();
			
			List menus = root.getChildren();
			
			for (int i=0;i<menus.size();i++)
			{
				Element menu = (Element)menus.get(i);
				
				Menu menuObj = new Menu();
				menuObj.setName(menu.getAttributeValue("name"));
				addMenu(menuObj);
				
				List menuItems = menu.getChildren();
				
				for (int y=0;y<menuItems.size();y++)
				{
					Element menuItem = (Element)menuItems.get(y);
					
					String display = menuItem.getAttributeValue("display");
					String link = menuItem.getAttributeValue("link");
					String logged_out = menuItem.getAttributeValue("logged_out");
					String logged_in = menuItem.getAttributeValue("logged_in");
					String roles = menuItem.getAttributeValue("roles");
					String roleList[] = roles.split(",");
					
					menuObj.addMenuItem(
							new MenuItem(display,link,logged_in,logged_out,roleList));
				}
			}
		}
		catch(Throwable e)
		{
			System.out.println("[FATAL ERROR]: could not load Simple URL mappings because: "+e);
			e.printStackTrace();
		}
		finally
		{
			if (is != null)
			{
				try
				{
					is.close();
				} catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}
	}
}
